package xiaolong.lian.exception;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.io.IOException;

/**
 * 自定义全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public String handleCustomException(CustomException e){
        JSONObject object = new JSONObject();
        object.put("msg",e.getMessage());
        return object.toJSONString();
    }

    @ExceptionHandler(value = { IOException.class , RuntimeException.class })
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public String handleServerException(Exception e){
        e.printStackTrace();
        JSONObject object = new JSONObject();
        object.put("msg", "服务器出了点小问题");
        return object.toJSONString();
    }
}
